package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.entity.MerchantFood;
import com.example.foodwebbackend.service.MerchantFoodService;
import com.example.foodwebbackend.service.UserRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/public")
@CrossOrigin(origins = "*")
public class PublicController {

    @Autowired
    private MerchantFoodService merchantFoodService;
    
    @Autowired
    private UserRatingService userRatingService;
    
    @Autowired
    private com.example.foodwebbackend.service.MerchantService merchantService;

    /**
     * 获取热门推荐菜品
     * 混合策略：hot_recommendation表 + 评分排序
     */
    @GetMapping("/popular-foods")
    public ApiResponse<List<Map<String, Object>>> getPopularFoods(
            @RequestParam(defaultValue = "6") Integer limit) {
        try {
            // 1. 先从hot_recommendation表获取推荐菜品
            List<MerchantFood> recommendedFoods = merchantFoodService.getHotRecommendations(limit);
            
            // 2. 如果推荐菜品不足，用评分最高的菜品补充
            if (recommendedFoods.size() < limit) {
                int remaining = limit - recommendedFoods.size();
                List<MerchantFood> topRatedFoods = merchantFoodService.getPopularFoods(remaining);
                
                // 避免重复添加
                Set<Integer> existingIds = new HashSet<>();
                for (MerchantFood food : recommendedFoods) {
                    existingIds.add(food.getFoodId());
                }
                
                for (MerchantFood food : topRatedFoods) {
                    if (!existingIds.contains(food.getFoodId()) && recommendedFoods.size() < limit) {
                        recommendedFoods.add(food);
                    }
                }
            }
            
            // 3. 转换为前端需要的格式，并计算真实评分
            List<Map<String, Object>> result = new ArrayList<>();
            for (MerchantFood food : recommendedFoods) {
                Map<String, Object> foodData = convertToFoodData(food);
                result.add(foodData);
            }
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error("获取热门推荐失败: " + e.getMessage());
        }
    }
    
    /**
     * 将MerchantFood转换为前端需要的数据格式
     */
    private Map<String, Object> convertToFoodData(MerchantFood food) {
        Map<String, Object> foodData = new HashMap<>();
        
        // 基本信息
        foodData.put("id", food.getFoodId());
        foodData.put("name", food.getFoodName());
        foodData.put("description", food.getFoodDescription());
        foodData.put("image", food.getFoodImagePath() != null ? food.getFoodImagePath() : "/food.png");
        foodData.put("merchant", food.getMerchantName());
        foodData.put("category", food.getCategoryName());
        foodData.put("price", food.getPrice());
        
        // 计算真实的评分和评论数
        try {
            List<Map<String, Object>> reviews = userRatingService.getFoodReviews(food.getFoodId());
            int reviewCount = reviews.size();
            double rating = 0.0;
            
            if (reviewCount > 0) {
                double sum = 0.0;
                for (Map<String, Object> review : reviews) {
                    Object ratingObj = review.get("rating");
                    if (ratingObj != null) {
                        if (ratingObj instanceof java.math.BigDecimal) {
                            sum += ((java.math.BigDecimal) ratingObj).doubleValue();
                        } else if (ratingObj instanceof Integer) {
                            sum += (Integer) ratingObj;
                        } else if (ratingObj instanceof Double) {
                            sum += (Double) ratingObj;
                        }
                    }
                }
                rating = sum / reviewCount;
                rating = Math.round(rating * 10.0) / 10.0; // 保留一位小数
            }
            
            foodData.put("rating", rating);
            foodData.put("reviewCount", reviewCount);
        } catch (Exception e) {
            // 如果获取评价失败，使用默认值
            foodData.put("rating", 0.0);
            foodData.put("reviewCount", 0);
        }
        
        return foodData;
    }

    /**
     * 调试API：获取所有商家（包含审核状态）
     */
    @GetMapping("/merchants/debug")
    public ApiResponse<List<Map<String, Object>>> getAllMerchantsDebug() {
        try {
            List<com.example.foodwebbackend.entity.Merchant> allMerchants = merchantService.getAllMerchants();
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (com.example.foodwebbackend.entity.Merchant merchant : allMerchants) {
                Map<String, Object> merchantMap = new HashMap<>();
                merchantMap.put("id", merchant.getMerchantId());
                merchantMap.put("name", merchant.getMerchantName());
                merchantMap.put("username", merchant.getUsername());
                merchantMap.put("isApproved", merchant.getIsApproved());
                merchantMap.put("approvalText", getApprovalText(merchant.getIsApproved()));
                result.add(merchantMap);
            }
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取商家调试信息失败: " + e.getMessage());
        }
    }
    
    private String getApprovalText(Integer isApproved) {
        if (isApproved == null) return "未知";
        switch (isApproved) {
            case 0: return "待审核";
            case 1: return "已通过";
            case 2: return "已拒绝";
            default: return "未知状态";
        }
    }

    /**
     * 一键审核所有商家 - 临时API
     */
    @PostMapping("/merchants/approve-all")
    public ApiResponse<String> approveAllMerchants() {
        try {
            List<com.example.foodwebbackend.entity.Merchant> allMerchants = merchantService.getAllMerchants();
            int approvedCount = 0;
            
            for (com.example.foodwebbackend.entity.Merchant merchant : allMerchants) {
                if (merchant.getIsApproved() != 1) {
                    merchantService.updateApprovalStatus(merchant.getMerchantId(), 1);
                    approvedCount++;
                }
            }
            
            return ApiResponse.success("成功审核通过 " + approvedCount + " 个商家");
        } catch (Exception e) {
            return ApiResponse.error("批量审核失败: " + e.getMessage());
        }
    }

    /**
     * 设置商家审核状态 - 临时测试API
     */
    @PostMapping("/merchants/{merchantId}/approval/{status}")
    public ApiResponse<String> setMerchantApprovalStatus(
            @PathVariable Integer merchantId, 
            @PathVariable Integer status) {
        try {
            if (status < 0 || status > 2) {
                return ApiResponse.error("审核状态值无效，应为0（待审核）、1（已通过）或2（已拒绝）");
            }
            
            com.example.foodwebbackend.entity.Merchant merchant = merchantService.findById(merchantId);
            if (merchant == null) {
                return ApiResponse.error("商家不存在");
            }
            
            merchantService.updateApprovalStatus(merchantId, status);
            String statusText = getApprovalText(status);
            
            return ApiResponse.success("商家 " + merchant.getMerchantName() + " 的审核状态已更新为：" + statusText);
        } catch (Exception e) {
            return ApiResponse.error("更新审核状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有商家列表（临时显示所有商家，不管审核状态）
     */
    @GetMapping("/merchants")
    public ApiResponse<List<Map<String, Object>>> getAllApprovedMerchants() {
        try {
            // 临时显示所有商家，不管审核状态
            List<com.example.foodwebbackend.entity.Merchant> merchants = merchantService.getAllMerchants();
            System.out.println("=== 商家列表调试信息 ===");
            System.out.println("数据库中总共有 " + merchants.size() + " 个商家");
            for (com.example.foodwebbackend.entity.Merchant m : merchants) {
                System.out.println("商家ID: " + m.getMerchantId() + 
                                 ", 名称: " + m.getMerchantName() + 
                                 ", 审核状态: " + m.getIsApproved() +
                                 " (" + getApprovalText(m.getIsApproved()) + ")");
            }
            
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (com.example.foodwebbackend.entity.Merchant merchant : merchants) {
                Map<String, Object> merchantMap = new HashMap<>();
                merchantMap.put("id", merchant.getMerchantId());
                merchantMap.put("name", merchant.getMerchantName());
                merchantMap.put("address", merchant.getMerchantAddress());
                merchantMap.put("phone", merchant.getContactPhone());
                merchantMap.put("businessHours", merchant.getBusinessHours());
                merchantMap.put("description", merchant.getMerchantDescription());
                merchantMap.put("image", merchant.getAvatarPath() != null ? merchant.getAvatarPath() : "/businessmen.png");
                
                // 解析特色标签
                List<String> features = new ArrayList<>();
                if (merchant.getFeatures() != null && !merchant.getFeatures().trim().isEmpty()) {
                    try {
                        // 尝试解析JSON格式
                        String featuresStr = merchant.getFeatures();
                        if (featuresStr.startsWith("[") && featuresStr.endsWith("]")) {
                            // JSON数组格式
                            featuresStr = featuresStr.substring(1, featuresStr.length() - 1);
                            String[] parts = featuresStr.split(",");
                            for (String part : parts) {
                                String feature = part.trim().replace("\"", "");
                                if (!feature.isEmpty()) {
                                    features.add(feature);
                                }
                            }
                        } else {
                            // 逗号分隔格式
                            String[] parts = featuresStr.split(",");
                            for (String part : parts) {
                                String feature = part.trim();
                                if (!feature.isEmpty()) {
                                    features.add(feature);
                                }
                            }
                        }
                    } catch (Exception e) {
                        // 解析失败，按逗号分割
                        String[] parts = merchant.getFeatures().split(",");
                        for (String part : parts) {
                            String feature = part.trim();
                            if (!feature.isEmpty()) {
                                features.add(feature);
                            }
                        }
                    }
                }
                merchantMap.put("features", features);
                
                // 获取菜系类型（基于该商家最常用的分类）
                try {
                    List<com.example.foodwebbackend.dto.MerchantFoodDto> foods = merchantFoodService.getMerchantFoods(merchant.getMerchantId());
                    String cuisine = "综合菜系";
                    if (!foods.isEmpty()) {
                        Map<String, Integer> categoryCount = new HashMap<>();
                        for (com.example.foodwebbackend.dto.MerchantFoodDto food : foods) {
                            if (food.getCategoryName() != null) {
                                categoryCount.put(food.getCategoryName(), 
                                    categoryCount.getOrDefault(food.getCategoryName(), 0) + 1);
                            }
                        }
                        
                        String mostCommonCategory = null;
                        int maxCount = 0;
                        for (Map.Entry<String, Integer> entry : categoryCount.entrySet()) {
                            if (entry.getValue() > maxCount) {
                                maxCount = entry.getValue();
                                mostCommonCategory = entry.getKey();
                            }
                        }
                        
                        if (mostCommonCategory != null) {
                            cuisine = mostCommonCategory;
                        }
                    }
                    merchantMap.put("cuisine", cuisine);
                } catch (Exception e) {
                    merchantMap.put("cuisine", "综合菜系");
                }
                
                result.add(merchantMap);
            }
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取商家列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取商家详情信息（包含菜品）
     */
    @GetMapping("/merchants/{merchantId}")
    public ApiResponse<Map<String, Object>> getMerchantDetail(@PathVariable Integer merchantId) {
        try {
            com.example.foodwebbackend.entity.Merchant merchant = merchantService.findById(merchantId);
            if (merchant == null) {
                return ApiResponse.error("商家不存在");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", merchant.getMerchantId());
            result.put("name", merchant.getMerchantName());
            result.put("address", merchant.getMerchantAddress());
            result.put("phone", merchant.getContactPhone());
            result.put("businessHours", merchant.getBusinessHours());
            result.put("description", merchant.getMerchantDescription());
            result.put("logo", merchant.getAvatarPath() != null ? merchant.getAvatarPath() : "/businessmen.png");
            
            // 添加审核状态信息
            result.put("isApproved", merchant.getIsApproved());
            result.put("approvalStatus", getApprovalText(merchant.getIsApproved()));
            result.put("canShowMenu", merchant.getIsApproved() == 1); // 只有审核通过才显示菜单
            
            // 解析特色标签
            List<String> features = new ArrayList<>();
            if (merchant.getFeatures() != null && !merchant.getFeatures().trim().isEmpty()) {
                try {
                    String featuresStr = merchant.getFeatures();
                    if (featuresStr.startsWith("[") && featuresStr.endsWith("]")) {
                        featuresStr = featuresStr.substring(1, featuresStr.length() - 1);
                        String[] parts = featuresStr.split(",");
                        for (String part : parts) {
                            String feature = part.trim().replace("\"", "");
                            if (!feature.isEmpty()) {
                                features.add(feature);
                            }
                        }
                    } else {
                        String[] parts = featuresStr.split(",");
                        for (String part : parts) {
                            String feature = part.trim();
                            if (!feature.isEmpty()) {
                                features.add(feature);
                            }
                        }
                    }
                } catch (Exception e) {
                    String[] parts = merchant.getFeatures().split(",");
                    for (String part : parts) {
                        String feature = part.trim();
                        if (!feature.isEmpty()) {
                            features.add(feature);
                        }
                    }
                }
            }
            result.put("features", features);
            
            // 获取商家菜品（只有审核通过才返回菜品）
            List<Map<String, Object>> menuItems = new ArrayList<>();
            if (merchant.getIsApproved() == 1) {
                List<com.example.foodwebbackend.dto.MerchantFoodDto> foods = merchantFoodService.getMerchantFoods(merchantId);
                
                for (com.example.foodwebbackend.dto.MerchantFoodDto food : foods) {
                    if (food.getIsActive()) { // 只返回上架的菜品
                        Map<String, Object> item = new HashMap<>();
                        item.put("id", food.getFoodId());
                        item.put("name", food.getFoodName());
                        item.put("price", food.getFoodPrice());
                        item.put("description", food.getFoodDescription());
                        item.put("image", food.getFoodImagePath() != null ? food.getFoodImagePath() : "/food.png");
                        item.put("categoryId", food.getCategoryId());
                        item.put("categoryName", food.getCategoryName());
                        menuItems.add(item);
                    }
                }
            }
            result.put("menuItems", menuItems);
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取商家详情失败: " + e.getMessage());
        }
    }
} 